package org.merak.core.web.mvc;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;

public final class PageControllerMap {

	//~ Attributes ///////////////////////////////////////////////////////////////
	//****************************************************************************
	private Map<String,PageController> map = new HashMap<String,PageController>(512);

	//~ Methods //////////////////////////////////////////////////////////////////
	//****************************************************************************
	public final synchronized PageController getController(String businessName)
		throws ServletException
	{
		// Look up for the controller
		PageController controller = this.map.get(businessName);

		// Initialize the controller on demand (lazily)
		if (controller == null) this.map.put(
			businessName,
			controller = this.newPageControler(businessName)
		);
		return controller;

	}
	//****************************************************************************
	public PageController newPageControler(String businessName)
		throws ServletException
	{

    	try {
    		// Find the class that handles the business logic
    		Class<?> businessClass = Class.forName(
    			MVCManager.getBusinessPackage() + '.' + businessName
    		);
    		// Initialize the controller
    		return new PageController(businessName,businessClass);
    	}
    	catch (ClassNotFoundException e) { throw new ServletException(
    		"The Business Logic doesn't exist: " + businessName,e
    	);}
    	catch (Exception e) { throw new ServletException(
    		"The Business Logic's Page Controller failed to initialized: " + businessName,e
    	);}

	}
	//****************************************************************************

}
